<!doctype html>
<html>
  <head>
    <title>Test GC of Closed AudioContext</title>
    <script src="../../resources/gc.js"></script>
    <script src="../../resources/testharness.js"></script>
    <script src="../../resources/testharnessreport.js"></script>
    <script src="../resources/audit-util.js"></script>
    <script src="../resources/audit.js"></script>
  </head>

  <body>
    <script>
      const audit = Audit.createTaskRunner();

      // Number of contexts to create for testing.  Fairly arbitrary, but should
      // be at least 6 (previous max allowed contexts) but not too many.
      const numberOfContexts = 10;

      audit.define('Test GC of Closed AudioContexts', (task, should) => {
        // Initial number of handlers.
        let initialCount = 0;
        asyncGC()
            .then(() => {
              initialCount = internals.audioHandlerCount();
              // For information only
              should(initialCount, 'Number of handlers before GC')
                  .beEqualTo(initialCount);
            })
            .then(() => {
              // Create a bunch of contexts for testing
              const contexts = [];
              for (let k = 0; k < numberOfContexts; ++k) {
                let c = new AudioContext();
                contexts.push(c.close());
                c = null;
              }

              // Wait for all the close methods to resolve before we check.
              Promise.all(contexts).then(() => {
                asyncGC()
                    .then(() => {
                      should(contexts.length, 'Number of contexts created')
                          .beEqualTo(numberOfContexts);
                      should(
                          internals.audioHandlerCount(),
                          'Number of handlers after GC')
                          .beEqualTo(initialCount);
                    })
                    .then(() => task.done());
              })
            });
      });

      audit.run();
    </script>
  </body>
</html>
